/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, removing the copyright
 * infomation is regarded as invassion of proprietary copyright
 ***********************************************************************/
package com.mr.qa.dao.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;

import com.mr.qa.bo.QuestionCategory;
import com.mr.qa.exception.QaException;

/**
 * Data access object (DAO) for domain model class QuestionCategory.
 * @see .QuestionCategory
 */
public class QuestionCategoryDAO extends BaseHibernateDAO 
{

    private static final Log log = LogFactory.getLog(QuestionCategoryDAO.class);

	//property constants
	public static final String NAME = "name";
	public static final String STATE = "state";

    
    public void save(QuestionCategory transientInstance) {
        log.debug("saving QuestionCategory instance");
        try {
            getSession().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
    
	public void delete(QuestionCategory persistentInstance) {
        log.debug("deleting QuestionCategory instance");
        try {
            getSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
	
	public void update(QuestionCategory transientInstance) {
        log.debug("update QuestionCategory instance");
        try {
            getSession().update(transientInstance);
            log.debug("update successful");
        } catch (RuntimeException re) {
            log.error("update failed", re);
            throw re;
        }
    }
    
    public QuestionCategory findById(Integer id) {
        try {
            QuestionCategory instance = (QuestionCategory) getSession()
                    .load("com.mr.qa.bo.QuestionCategory", id);
            return instance;
        } catch (RuntimeException re) {
            throw re;
        }
    }
    
    public int countQuestions(int categoryId) throws QaException
    {
        try
        {
            String queryString = "select count(*) from Question as model where model.mrIaskCategory.id = ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, categoryId);
            long longCount = (Long)queryObject.uniqueResult();
            return (int)longCount;            
        }
        catch (RuntimeException re)
        {
            throw re;
        }
        
    }
    
    /**
     * find questions by Question Category Id for admin
     * @return 
     */
        
    public List findQuestions(Integer categoryId) throws Exception
    {
        try
        {
            String queryString = "from Question as model where model.mrIaskCategory.id = ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, categoryId);
            if(this.getPageNo().intValue() > 0 && this.getRecordCount().intValue() > 0){
                    queryObject.setFirstResult((getPageNo().intValue() - 1) * getRecordCount().intValue());
                    queryObject.setMaxResults(getPageNo().intValue() * getRecordCount().intValue());
            }
            return queryObject.list();
        }
        catch(Exception re) 
        {
            throw re;
        }
    }      
    
    /**
     * 2007-4-23 this method need adjusted
     * @return 
     */
        
    public List findAll() 
    {
        try 
        {
        	return findAll("order by model.priority desc");
        }
        catch (RuntimeException re) 
        {
            log.error("find by example failed", re);
            throw re;
        }
    } 
    
    public List findAll(String orderBy) 
    {
        try 
        {
        	String sql = "from QuestionCategory as model where model.mrIaskCategory is null ";
        	if(orderBy != null){
        		sql += orderBy;
        	}
            Query queryObject = getSession().createQuery("from QuestionCategory as model where model.mrIaskCategory is null");
            queryObject.setCacheable(true);
            return queryObject.list();
        }
        catch (RuntimeException re) 
        {
            log.error("find by example failed", re);
            throw re;
        }
    } 
    
    public List findByType(Integer type) 
    {
    	if(type == null){
    		return findAll();
    	}
        try 
        {
            Query queryObject = getSession().createQuery("from QuestionCategory as model where model.mrIaskCategory is null and model.type =:type order by model.priority desc");
            //queryObject.setCacheable(true);
            queryObject.setParameter("type", type);
            return queryObject.list();
        }
        catch (RuntimeException re) 
        {
            log.error("find by example failed", re);
            throw re;
        }
    }  
    
    
    public List findByExample(QuestionCategory instance) {
        log.debug("finding QuestionCategory instance by example");
        try {
            List results = getSession()
                    .createCriteria("com.mr.qa.bo.QuestionCategory")
                    .add(Example.create(instance))
            .list();
            log.debug("find by example successful, result size: " + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }    
    
    public List findByProperty(String propertyName, Object value) {
      log.debug("finding QuestionCategory instance with property: " + propertyName
            + ", value: " + value);
      try {
         String queryString = "from QuestionCategory as model where model." 
         						+ propertyName + "= ?";
         Query queryObject = getSession().createQuery(queryString);
		 queryObject.setParameter(0, value);
		 return queryObject.list();
      } catch (RuntimeException re) {
         log.error("find by property name failed", re);
         throw re;
      }
	}

	public List findByName(Object name) {
		return findByProperty(NAME, name);
	}
	
	public List findByState(Object state) {
		return findByProperty(STATE, state);
	}
	
    public QuestionCategory merge(QuestionCategory detachedInstance) {
        log.debug("merging QuestionCategory instance");
        try {
            QuestionCategory result = (QuestionCategory) getSession()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(QuestionCategory instance) {
        log.debug("attaching dirty QuestionCategory instance");
        try {
            getSession().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
    
    public void attachClean(QuestionCategory instance) {
        log.debug("attaching clean QuestionCategory instance");
        try {
            getSession().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
}